<template>
  <div>
    <a-form-model ref="form" :model="model" :rules="validatorRules">
      <a-form-model-item required prop="phone">
        <a-input v-model="model.phone" size="large" type="text" placeholder="请输入手机号">
          <a-icon slot="prefix" type="mobile" :style="{ color: '#022EA0' }"/>
        </a-input>
      </a-form-model-item>
      <a-form-model-item required prop="password">
        <a-input-password v-model="model.password" size="large" allow-clear autocomplete="false" placeholder="请输入密码">
          <a-icon slot="prefix" type="lock" :style="{ color: '#022EA0' }"/>
        </a-input-password>
      </a-form-model-item>
<!--      <a-form-model-item required prop="captcha">
        <a-input v-model="model.captcha" style="width: 160px" size="large" type="text" placeholder="验证码">
          <a-icon slot="prefix" type="mail" :style="{ color: '#022EA0' }"/>
        </a-input>
        <a-button
          class="getCaptcha"
          tabindex="-1"
          :disabled="state.smsSendBtn"
          @click.stop.prevent="getCaptcha"
          v-text="!state.smsSendBtn && '获取验证码' || (state.time+' s后再次获取')"></a-button>
      </a-form-model-item>-->
      <a-row :gutter="0">
        <a-col :span="16">
          <a-form-model-item required prop="inputCode">
            <a-input v-model="model.inputCode" size="large" type="text" placeholder="请输入验证码" autocomplete="off">
              <a-icon slot="prefix" type="mail" :style="{ color: '#022EA0' }"/>
            </a-input>
          </a-form-model-item>
        </a-col>
        <a-col :span="8" style="text-align: right">
          <img v-if="requestCodeSuccess" style="margin-top: 2px;" :src="randCodeImage" @click="handleChangeCheckCode"/>
          <img v-else style="margin-top: 2px;" src="../../assets/checkcode.png" @click="handleChangeCheckCode"/>
        </a-col>
      </a-row>
    </a-form-model>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { getAction } from '@/api/manage'
import { encryptIt } from '@/utils/util'
export default {
  name: 'LoginPhone',
  data(){
    return {
      my:null,
      myTest:'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCs7eVl3hduxnpyKhwI27seelA6cfr0ghTFVsMuaFW68KDa0Xv3NANEQ1YjWYVM/AUllHSDq0ORdIGm2suKCsmGuLnDK1TK7LbOZLgvkDz+Ft+06Y0ZzjILzl0SUtawE+fD6dpebAeD+dOAcl9EzU536ASLx0rsziOZIwcN3aWx5wIDAQAB',
      myPro:'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDpIyqMNYBRzfwVhL+P6jav7rGkNZQ0nu+7G7qe1g7mThM9D6Dc717sN1ATDgPxJzgI+NEQ+wx2B1HpUcs4pigyXbnL96qgHrsTe6ZX9YyicsaLz5FM7nujypfVAkfr/VQLEA8z9L7XsAh+Hm6g0WCdSPqdWHY0lS0ImOXth3PgjwIDAQAB',
      requestCodeSuccess: false,
      randCodeImage: '',
      currdatetime: '',
      model:{
        phone: '',
        password:'',
        inputCode:''
      },
      //手机号登录用
      state: {
        time: 60,
        smsSendBtn: false,
      },
      validatorRules:{
        phone: [
          { required: true, message: '请输入手机号码!' },
          { validator: this.validatePhone }
        ],
        password: [{
          required: true, message: '请输入密码!', validator: 'click'
        }],
        inputCode: [{
          required: true, message: '请输入验证码!'
        }]
      }

    }
  },
  created() {
    this.handleChangeCheckCode();
  },
  methods:{
    ...mapActions(['PhoneLogin']),
    ...mapActions(['Login']),
    /**刷新验证码*/
    handleChangeCheckCode(){
      this.currdatetime = new Date().getTime();
      this.model.inputCode = ''
      getAction(`/sys/randomImage/${this.currdatetime}`).then(res=>{
        if(res.success){
          this.randCodeImage = res.result
          this.requestCodeSuccess=true
        }else{
          this.$message.error(res.message)
          this.requestCodeSuccess=false
        }
      }).catch(()=>{
        this.requestCodeSuccess=false
      })
    },
    handleLogin(rememberMe){
      this.validateFields([ 'phone', 'inputCode' ], (err) => {
        if (!err) {
          let loginParams = {
            phone: this.model.phone,
            password: this.model.password,
            captcha: this.model.inputCode,
            checkKey: this.currdatetime,
            remember_me: rememberMe
          }
          // console.log("登录参数", loginParams)
          if(process.env.VUE_APP_MY_STR == 'test'){
            this.my = this.myTest
            loginParams.password = encryptIt(this.my,loginParams.password)
          }else if(process.env.VUE_APP_MY_STR == 'pro'){
            this.my = this.myPro
            loginParams.password = encryptIt(this.my,loginParams.password)
          }
          this.PhoneLogin(loginParams).then((res) => {
            this.$emit('success', res.result)
          }).catch((err) => {
            this.$emit('fail', err)
          });
        }else{
          this.$emit('validateFail')
        }
      })
    },
    // 校验手机号
    validatePhone(rule,value,callback){
      let reg = /^(1\d{10})$/;
      if (!value || reg.test(value)){
        callback();
      }else{
        callback("您的手机号码格式不正确!");
      }
    },
    //获取验证码
    getCaptcha (e) {
      e.preventDefault();
      let that = this;
      that.validateFields([ 'phone' ], (err) => {
          if (!err) {
            that.state.smsSendBtn = true;
            let interval = window.setInterval(() => {
              if (that.state.time-- <= 0) {
                that.state.time = 60;
                that.state.smsSendBtn = false;
                window.clearInterval(interval);
              }
            }, 1000);

            const hide = that.$message.loading('验证码发送中..', 0);
            let smsParams = {};
            smsParams.transCode='1001';
            smsParams.phone=that.model.phone;
            // smsParams.smsmode="0";
            getAction("/cloud/third/sms/sendSMSCode",smsParams)
              .then(res => {
                if(!res.success){
                  setTimeout(hide, 0);
                  that.cmsFailed(res.message);
                }
                console.log(res);
                setTimeout(hide, 500);
              })
              .catch(err => {
                setTimeout(hide, 1);
                clearInterval(interval);
                that.state.time = 60;
                that.state.smsSendBtn = false;
                that.requestFailed(err);
              });
          }
        }
      );
    },
    cmsFailed(err){
      this.$notification[ 'error' ]({
        message: '获取验证码失败',
        description:err,
        duration: 4,
      });
    },
    /**
     * 验证字段
     * @param arr
     * @param callback
     */
    validateFields(arr, callback){
      let promiseArray = []
      for(let item of arr){
        let p = new Promise((resolve, reject) => {
          this.$refs['form'].validateField(item, (err)=>{
            if(!err){
              resolve();
            }else{
              reject(err);
            }
          })
        });
        promiseArray.push(p)
      }
      Promise.all(promiseArray).then(()=>{
        callback()
      }).catch(err=>{
        callback(err)
      })
    },


  }

}
</script>

<style scoped lang="less">
/deep/.ant-form-item-children{
  display: flex;
  align-items: center;
  justify-content: space-between;
}
/deep/.ant-form-explain{
  text-align: left;
  margin-top: 2px;
}
.getCaptcha {
  display: block;
  //width: 100%;
  height: 40px;
}
</style>
